package oa.system

import grails.gorm.DetachedCriteria
import groovy.transform.ToString
import org.codehaus.groovy.util.HashCodeHelper
import grails.compiler.GrailsCompileStatic

@GrailsCompileStatic
@ToString(cache=true, includeNames=true, includePackage=false)
class OpAuthGroup implements Serializable {

	private static final long serialVersionUID = 1

	Op op
	AuthGroup authGroup

	@Override
	boolean equals(other) {
		if (other instanceof OpAuthGroup) {
			other.opId == op?.id && other.authGroupId == authGroup?.id
		}
	}

    @Override
	int hashCode() {
	    int hashCode = HashCodeHelper.initHash()
        if (op) {
            hashCode = HashCodeHelper.updateHash(hashCode, op.id)
		}
		if (authGroup) {
		    hashCode = HashCodeHelper.updateHash(hashCode, authGroup.id)
		}
		hashCode
	}
	
	static OpAuthGroup get(long opId, long authGroupId) {
		criteriaFor(opId, authGroupId).get()
	}

	static boolean exists(long opId, long authGroupId) {
		criteriaFor(opId, authGroupId).count()
	}

	private static DetachedCriteria criteriaFor(long opId, long authGroupId) {
		OpAuthGroup.where {
			op == Op.load(opId) &&
			authGroup == AuthGroup.load(authGroupId)
		}
	}

	static OpAuthGroup create(Op op, AuthGroup authGroup, boolean flush = false) {
		def instance = new OpAuthGroup(op: op, authGroup: authGroup)
		instance.save(flush: flush)
		instance
	}

	static boolean remove(Op u, AuthGroup rg) {
		if (u != null && rg != null) {
			OpAuthGroup.where { op == u && authGroup == rg }.deleteAll()
		}
	}

	static int removeAll(Op u) {
		u == null ? 0 : OpAuthGroup.where { op == u }.deleteAll() as int
	}

	static int removeAll(AuthGroup rg) {
		rg == null ? 0 : OpAuthGroup.where { authGroup == rg }.deleteAll() as int
	}

	static constraints = {
	    authGroup nullable: false
		op nullable: false, validator: { Op u, OpAuthGroup ug ->
			if (ug.authGroup?.id) {
				if (OpAuthGroup.exists(u.id, ug.authGroup.id)) {
					return ['userGroup.exists']
				}
			}
		}
	}

	static mapping = {
		id composite: ['authGroup', 'op']
		version false
	}
}
